package com.tmc.service.map;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.map.QueryAddressResp;
import com.tmc.bean.map.Result;
import com.tmc.util.HttpClientUtil;
import com.tmc.util.ObjectUtil;

/**
 * @author zhang
 * @date 2018年1月10日 下午2:21:08 
 */
@Service
public class GoogleMapsServiceImpl {
	
	private Log log = LogFactory.getLog(this.getClass());
	
	
	public CommonResult getLocations(ContextInfo context, String address){
		if(ObjectUtil.noText(address)){
			return CommonResult.makeFail("请输入查询地址！");
		}
		String addressEncoder = ""; 
		try {
			addressEncoder = URLEncoder.encode(address,"utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("查询地址参数转编码错误！", e);
		}
		JSONArray jsonArray = null;
		try {
			String url="https://maps.google.com/maps/api/geocode/json?address="+addressEncoder+"&sensor=true&language=zh-CN&key=AIzaSyAv4VD0PW5lX7wA8hom9_zp5yk5O8iYXDk";
			String jsonString = HttpClientUtil.sendHttpGetToGoogle(url);
			if(ObjectUtil.noText(jsonString)){
				return CommonResult.makeFail("查询失败！");
			}
			QueryAddressResp resp = JSON.parseObject(jsonString, QueryAddressResp.class);
			jsonArray = this.toJSONArray(resp);
		} catch (Exception e) {
			log.error("", e);
			return CommonResult.makeFail("未能正常连接google！");
		}
		return CommonResult.makeSuccess("操作成功！", jsonArray);
	}
	
	private JSONArray toJSONArray(QueryAddressResp resp){
		JSONArray jsonArray = new JSONArray();
		if(resp.getStatus().equals("OK")){
			for (Result result : resp.getResults()) {
				JSONObject obj = new JSONObject();
				if(result.getFormatted_address().lastIndexOf("邮政编码:")>-1){
					obj.put("fromAddress", result.getFormatted_address().substring(0, result.getFormatted_address().lastIndexOf("")));
				}else{
					obj.put("fromAddress", result.getFormatted_address());
				}
				obj.put("longitude", result.getGeometry().getLocation().getLng());
				obj.put("latitude", result.getGeometry().getLocation().getLat());
				obj.put("placeID", result.getPlace_id());
				//obj.put("name", result);
				jsonArray.add(obj);
			}
		}
		return jsonArray;
	}
}